package com.trailwalker.javafx.utils.resource;

import com.trailwalker.javafx.utils.system.OSUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Trailwalker
 * @create 2021-08-31 14:44
 * @des
 */
public class ResourceUtils {

    private static final String TAG = ResourceUtils.class.getSimpleName();

    /**
     * 获取图片资源
     *
     * @param name
     * @return
     */
    public static String getImage(Object object, String name) {
        return object.getClass().getResource("/image/" + name).toExternalForm();
    }

    /**
     * 获取音乐资源
     *
     * @param name
     * @return
     */
    public static String getMusic(Object object, String name) {
        return object.getClass().getResource("/music/" + name).toExternalForm();
    }

    /**
     * 获取css资源
     *
     * @param name
     * @return
     */
    public static String getCss(Object object, String name) {
        return object.getClass().getResource("/css/" + name).toExternalForm();
    }

    public static File getToolResourceFile(Object object, String fileName) {
        InputStream resourceStream = object.getClass().getResourceAsStream("/tools/" + fileName);
        int os = OSUtils.getOS();
        if (OSUtils.WINDOWS == os) {

        } else if (OSUtils.MAC_OS == os) {
            if (OSUtils.isX86()) {
                System.err.println("暂不支持该系统: " + OSUtils.getOSName());
                return null;
            }
        } else {
            System.err.println("暂不支持该系统: " + OSUtils.getOSName());
            return null;
        }
        //保存到项目目录下
        File tmpFile = new File(System.getProperty("user.dir"), "tools" + File.separator + fileName);
        if (!tmpFile.exists()) {
            int index;
            byte[] bytes = new byte[1024];
            FileOutputStream fileOutputStream;
            try {
                fileOutputStream = new FileOutputStream(tmpFile);
                while ((index = resourceStream.read(bytes)) != -1) {
                    fileOutputStream.write(bytes, 0, index);
                    fileOutputStream.flush();
                }
                resourceStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return tmpFile;
    }

}
